//
//  DanpinCell.m
//  danpin
//
//  Created by chuangjia on 22/10/2015.
//  Copyright © 2015 chuangjia. All rights reserved.
//

#import "DanpinCell.h"

#import "CalcLabel.h"
#import "appdelegate.h"
#import "TTTAttributedLabel.h"
#import "UILabel+StringFrame.h"
@interface DanpinCell ()
{
    
}
@property(nonatomic,strong) TTTAttributedLabel *title;
@property(nonatomic,strong)UIImageView *titleIcon;
@property(nonatomic,strong)UILabel *price;
@property(nonatomic,strong)UIButton *buyBtn;
@property(nonatomic,strong)UIImageView *lineView;
@end
@implementation DanpinCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self)
    {
        
        _title =[[TTTAttributedLabel alloc] initWithFrame:CGRectMake(0,0, DEVICE_WIDTH-PHOTO_FRAME_WIDTH*11,0)];
        _title.backgroundColor = [UIColor clearColor];
        _title.textColor = [UIColor darkTextColor];//UIColorFromRGB(0x808080);
        _title.textAlignment = NSTextAlignmentLeft;
        _title.lineBreakMode = NSLineBreakByWordWrapping|NSLineBreakByTruncatingTail;
        
        _title.numberOfLines=0;
        _title.font = FONT(14);
        [self.contentView addSubview:_title];
        
        
        _titleIcon =[[UIImageView alloc] initWithFrame:CGRectZero];
        _titleIcon.contentMode = UIViewContentModeScaleAspectFit;
        [self.contentView addSubview:_titleIcon];
        
        _price =[[UILabel alloc] initWithFrame:CGRectZero];
        _price.backgroundColor = [UIColor clearColor];
        _price.textColor = [UIColor darkGrayColor];
        _price.textAlignment = NSTextAlignmentLeft;
        _price.font =  FONT(13);
        _price.numberOfLines=0;
        [self.contentView addSubview:_price];
      
        
        _buyBtn =[UIButton buttonWithType:UIButtonTypeCustom];
        [_buyBtn setImage:[UIImage imageNamed:@"arrow-right.png"] forState:UIControlStateNormal];
        [_buyBtn addTarget:self action:@selector(commentAction) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:_buyBtn];
        
        _lineView =[[UIImageView alloc] initWithFrame:CGRectZero];
        _lineView.backgroundColor=UIColorFromRGB(0xe5e5e5);
        [self.contentView addSubview:_lineView];
    }
    return self;
}
-(void)dealloc
{
    self.data=nil;
    self.title=nil;
    self.price=nil;
    self.buyBtn=nil;
    [self.lineView removeFromSuperview];
    self.lineView=nil;
    //    DLog(@"%s", __PRETTY_FUNCTION__);
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
}
- (void)drawRect:(CGRect)rect {
    
    [super drawRect:rect];
    self.lineView.frame =CGRectMake(0, self.bounds.size.height-0.5, DEVICE_WIDTH, 0.5);
    
}

/// 根据数据模型来显示内容
- (void)showInfo:(id)model other:(id)other key:(id)key indexPath:(NSIndexPath *)indexPath
{
    self.other=other;
    self.key = key;
    self.indexPath=indexPath;
    NSDictionary *dict =(NSDictionary*)model;
    self.data =model;
    
    self.titleIcon.frame =CGRectMake(PHOTO_FRAME_WIDTH,PHOTO_FRAME_WIDTH, PHOTO_FRAME_WIDTH*10, PHOTO_FRAME_WIDTH*10);
    NSString *imag =[dict stringForKey:@"image_url" withDefaultValue:@""];
    NSString *imag_data =[dict stringForKey:@"image_data" withDefaultValue:@""];
    if (imag.length>0 ) {
        
        self.titleIcon.image = nil;
        
        [self.titleIcon sd_setImageWithURL:[NSURL URLWithString:imag]
                                 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                                     if(image)
                                         [self.titleIcon.layer addAnimation:[CATransition animation] forKey:kCATransition];
                                     else
                                         self.titleIcon.image=[UIImage imageNamed:@"image.png"];
                                 }];
        
    }else if(imag_data.length>0)
    {
        self.titleIcon.image =[self base64DecodeImageWithString:imag_data];
    }else
    {
        self.titleIcon.image=[UIImage imageNamed:@"image.png"];
    }
    
    __weak typeof (self) wSelf = self;
    NSString *title =[dict stringForKey:@"title" withDefaultValue:@""];
    if(title.length>0)
    {
        
        [self.title setText:title afterInheritingLabelAttributesAndConfiguringWithBlock:^ NSMutableAttributedString  *(NSMutableAttributedString *attributedString)
         {
             
         //    CTFontRef helveticaBold = CTFontCreateWithName((CFStringRef)FONT_NAME, 14 ,NULL);
         //    [attributedString addAttribute:(id)kCTFontAttributeName value:(__bridge id)helveticaBold range:NSMakeRange(0,[attributedString length])];
             [attributedString addAttribute:NSFontAttributeName
                                      value:wSelf.title.font
                                      range:NSMakeRange(0,[attributedString length])];

             
             //设置字体颜色
             [attributedString addAttribute:(id)kCTForegroundColorAttributeName value:TITLE_COLOR range:NSMakeRange(0,[attributedString length])];
             
             
             
             NSArray* words = [wSelf.data arrayObjectForKey:@"words"];
             if(words && [words isKindOfClass:[NSArray class]])
             {
                 for(int i = 0; i < [words count]; i++)
                 {
                     
                     
                     NSString* strWord = [words objectAtIndex:i];
                     NSRange range = [[attributedString string] rangeOfString:strWord options:NSCaseInsensitiveSearch];
                     
                     if (range.location != NSNotFound)
                     {
                         [attributedString addAttribute:(id)kCTForegroundColorAttributeName
                                                  value:HILIGHT_COLOR//UIColorFromRGB(0xCE0202)//[UIColor redColor]
                                                  range:range];
                         
                     }
                 }
             }
             
     //        CFRelease(helveticaBold);
             return attributedString;
             
         }];
        float fheight = [CalcLabel getAttributedStringHeightWidthValue:(DEVICE_WIDTH-PHOTO_FRAME_WIDTH*13) str:self.title.attributedText];
        if (fheight>43) {
            fheight=43;
        }
        self.title.frame =CGRectMake(PHOTO_FRAME_WIDTH*12,PHOTO_FRAME_WIDTH, DEVICE_WIDTH-PHOTO_FRAME_WIDTH*13, fheight);
        NSString *comment =[dict stringForKey:@"text" withDefaultValue:@""];
        if (comment.length>0) {
            self.price.text =comment;
            CGSize size = [self.price boundingRectWithSize:CGSizeMake(DEVICE_WIDTH-PHOTO_FRAME_WIDTH*13, 0)];
            float fheight1 =size.height;
            float h =PHOTO_FRAME_WIDTH*12 -fheight - PHOTO_FRAME_WIDTH*3;
            if (fheight1 > h ) {
                fheight1 =h;
            }
            self.price.frame =CGRectMake(PHOTO_FRAME_WIDTH*12,PHOTO_FRAME_WIDTH*1.5+fheight, DEVICE_WIDTH-PHOTO_FRAME_WIDTH*13, fheight1);
        }else
        {
            self.price.text =@"";
        }
    }
  
    [self layoutSubviews];
}
/// 返回Cell高度
+ (CGFloat)returnCellHeight:(id)model
{
    return PHOTO_FRAME_WIDTH*12;
}
-(void)setCallBack:(void(^)(BEventType,UIView*,id,id,NSIndexPath *))callback
{
    self.actionBlock=callback;
}
-(void)commentAction
{
    if (self.actionBlock)
    {
        self.actionBlock(BEventType_taobao,nil,self.data,self.key,self.indexPath);
    }
}
-(UIImage*)base64image:(NSString *)data
{
    NSData* xmlData = [data dataUsingEncoding:NSUTF8StringEncoding];
    UIImage *image = [UIImage imageWithData:xmlData];
    return image;
}
//处理web端的图片数据为nsdata 格式数据
-(UIImage *)base64DecodeImageWithString:(NSString*)base64str
{
    NSData* dataFromString = [[NSData alloc] initWithBase64EncodedString:base64str options:0];
    UIImage *imagess =[UIImage imageWithData:dataFromString];
    dataFromString=nil;
    return imagess;
}
@end
